package com.zhifa.controller;

import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.sun.org.apache.bcel.internal.generic.NEW;
import com.zhifa.Util.DateJsonValueProcessor;
import com.zhifa.Util.DateUtil;
import com.zhifa.Util.ResponseUtil;
import com.zhifa.Util.StringUtil;
import com.zhifa.entity.DateTime;
import com.zhifa.entity.PageBean;
import com.zhifa.entity.Salaryitem;
import com.zhifa.entity.Staff;
import com.zhifa.service.InstitutionService;
import com.zhifa.service.PositionService;
import com.zhifa.service.SalaryitemService;
import com.zhifa.service.SalarystandardService;
import com.zhifa.service.StaffService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

@Controller
@RequestMapping("/staff")
public class StaffController {

	@Resource
	StaffService staffService;
	
	@Resource
	InstitutionService institutionService;
	
	@Resource
	PositionService positionService;
	
	@Resource
	SalarystandardService salarystandardService;
	
	@Resource
	SalaryitemService salaryitemService;
	
	@InitBinder  
	public void initBinder(WebDataBinder binder) {  
		//yyyy-MM-dd HH:mm:ss
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
		dateFormat.setLenient(false);  
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   //true:允许输入空值，false:不能为空值
	}

	@RequestMapping("/save")
	public String addStaff(Staff staff,@RequestParam(value="imgfile",required=false) MultipartFile imgfile, HttpServletRequest request,HttpServletResponse response)throws Exception{
        //获得物理路径webapp所在路径  
        if(!imgfile.isEmpty()){  
           //员工id作为新的新文件名的标识
          //  String fileName =imgfile.getOriginalFilename() ;  
            // 新文件名  
           // String newFileName =currentAdmin.getId()+fileName; 
            String filePath=request.getServletContext().getRealPath("/");
        	//String filePath="E:\\hrpicture\\";
            UUID randomUUID = UUID.randomUUID();
            String string = randomUUID.toString();
            String img=string+imgfile.getOriginalFilename();
            staff.setImg(img);
    		imgfile.transferTo(new File(filePath+img));
           // imgfile.transferTo(new File(filePath+"staffimg/"+newFileName));
        }  
        int addStaffcount = staffService.addStaff(staff);
        JSONObject result=new JSONObject();
		if(addStaffcount>0){ 
			result.put("success", true);
		}else{
			result.put("success", false);
		}
		ResponseUtil.write(response, result);
		return null;
		
	}
	
	@RequestMapping("/change")
	public String changeStaff(Staff staff,@RequestParam(value="imgfile",required=false) MultipartFile imgfile, HttpServletRequest request,HttpServletResponse response)throws Exception{
     //获得物理路径webapp所在路径  
     if(!imgfile.isEmpty()){  
        //员工id作为新的新文件名的标识
       //  String fileName =imgfile.getOriginalFilename() ;  
         // 新文件名  
        // String newFileName =currentAdmin.getId()+fileName; 
         String filePath=request.getServletContext().getRealPath("/");
     	//String filePath="E:\\hrpicture\\";
         UUID randomUUID = UUID.randomUUID();
         String string = randomUUID.toString();
         String img=string+imgfile.getOriginalFilename();
         staff.setImg(img);
 		imgfile.transferTo(new File(filePath+img));
        // imgfile.transferTo(new File(filePath+"staffimg/"+newFileName));
     }  
     String changeState = request.getParameter("changeState");
     int addStaffcount =0;
     if (StringUtil.isEmpty(changeState)) {
    	 
    	  addStaffcount = staffService.updateStaff(staff);
	}else if (Integer.parseInt(changeState)==1) {
		  staff.setState("正常");
		  addStaffcount=staffService.changeState(staff);
	}
     JSONObject result=new JSONObject();
		if(addStaffcount>0){ 
			result.put("success", true);
		}else{
			result.put("success", false);
		}
		ResponseUtil.write(response, result);
		return null;
		
	}
	
	@RequestMapping("/delete")
	public String deleteState(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String state = request.getParameter("changeState");
		String id = request.getParameter("id");
		Staff staff=new Staff();
		staff.setId(Integer.parseInt(id));
		staff.setState(state);
		int changeState = staffService.changeState(staff);
		 JSONObject result=new JSONObject();
			if(changeState>0){ 
				result.put("success", true);
			}else{
				result.put("success", false);
			}
			ResponseUtil.write(response, result);
			return null;
	}
	
	
	@RequestMapping("/getListByMap")
	public String getListByMap(Staff staff,DateTime dateTime,@RequestParam(value="page",required=false)String page,@RequestParam(value="rows",required=false)String rows,HttpServletRequest request,HttpServletResponse response) throws Exception{
		PageBean pageBean=new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
		Map<String, Object>map=new HashMap<String, Object>();
		map.put("fmechanism", staff.getFmechanism());
		map.put("smechanism", staff.getSmechanism());
		map.put("tmechanism", staff.getTmechanism());
		map.put("posc", staff.getPosc());
		map.put("posn", staff.getPosn());
		map.put("state", staff.getState());
		map.put("starttime",DateUtil.formatDate(dateTime.getStarttime(), "yyyy-MM-dd HH:mm:ss"));
		map.put("endtime", DateUtil.formatDate(dateTime.getEndtime(), "yyyy-MM-dd HH:mm:ss"));
		map.put("start", pageBean.getStart());
		map.put("size", pageBean.getPageSize());
		List<Staff> listByMap = staffService.getListByMap(map);
		long counts = staffService.getCounts(map);
		JSONObject result=new JSONObject();
		JsonConfig jsonConfig=new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
		JSONArray jsonArray=JSONArray.fromObject(listByMap,jsonConfig);
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			String fmechanism = listByMap.get(i).getFmechanism();
			String smechanism = listByMap.get(i).getSmechanism();
			String tmechanism = listByMap.get(i).getTmechanism();
			String posc = listByMap.get(i).getPosc();
			String posn = listByMap.get(i).getPosn();
			if (!StringUtil.isEmpty(fmechanism)) {
				jsonObject.put("fmechanism", institutionService.findNameById(Integer.parseInt(fmechanism)));
			}
			if (!StringUtil.isEmpty(smechanism)) {
				jsonObject.put("smechanism", institutionService.findNameById(Integer.parseInt(smechanism)));
			}
			if (!StringUtil.isEmpty(tmechanism)) {
				jsonObject.put("tmechanism", institutionService.findNameById(Integer.parseInt(tmechanism)));
			}
			if (!StringUtil.isEmpty(posc)) {
				jsonObject.put("posc", positionService.findNameById(Integer.parseInt(posc)));
			}
			if (!StringUtil.isEmpty(posn)) {
				jsonObject.put("posn", positionService.findNameById(Integer.parseInt(posn)));
			}
			
			
		}
		result.put("rows", jsonArray);
		result.put("total", counts);
		ResponseUtil.write(response, result);
		return null;
	}

	@RequestMapping("/findEntry")
	public String findEntry(HttpServletResponse response) throws Exception{
		List<Staff> findEntry = staffService.findEntry();
		JSONArray jsonArray = JSONArray.fromObject(findEntry);
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			
			String fmechanism = findEntry.get(i).getFmechanism();
			String smechanism = findEntry.get(i).getSmechanism();
			String tmechanism = findEntry.get(i).getTmechanism();
			
			
			if (!StringUtil.isEmpty(fmechanism)) {
				jsonObject.put("fmid", fmechanism);
				jsonObject.put("fmechanism", institutionService.findNameById(Integer.parseInt(fmechanism)));
			}
			if (!StringUtil.isEmpty(smechanism)) {
				jsonObject.put("smid", smechanism);
				jsonObject.put("smechanism", institutionService.findNameById(Integer.parseInt(smechanism)));
			}
			if (!StringUtil.isEmpty(tmechanism)) {
				jsonObject.put("tmid", tmechanism);
				jsonObject.put("tmechanism", institutionService.findNameById(Integer.parseInt(tmechanism)));
			}
			/*
			 * 获取总金额
			 */
			Double money=0.00;
			Staff total=new Staff();
			total.setFmechanism(fmechanism);
			total.setSmechanism(smechanism);
			total.setTmechanism(tmechanism);
			/*
			 * 按照机构分组条件，能查到每个分组的total值
			 */
			List<Staff> staffs = staffService.getStaffByInstitution(total);
			for (int j = 0; j < staffs.size(); j++) {
				Staff listStaff = staffs.get(j);
				String name = listStaff.getSalarystandard();
				String timestamp = salarystandardService.gettimestampByName(name);
				List<Salaryitem> salaryitemlist = salaryitemService.findSalaryitemByTimestamp(timestamp);
				for (int k = 0; k <salaryitemlist.size(); k++) {
					Salaryitem salaryitem = salaryitemlist.get(k);
					
					money+=salaryitem.getMoney();
				}
				
			}
			jsonObject.put("total", new DecimalFormat("#.00").format(money));
		}
//		JSONObject result=new JSONObject();
//		result.put("rows", jsonArray);
		ResponseUtil.write(response, jsonArray);
		return null;
	}
	/*
	 * 
	 */
	//@RequestMapping("/getStaffByInstitution")
	@RequestMapping(value = "/getStaffByInstitution", method = RequestMethod.POST, produces = {"application/json;","text/html;charset=UTF-8;"}) 
	public String getStaffByInstitution(Staff staff,HttpServletRequest request,HttpServletResponse response) throws Exception{
		//request.setCharacterEncoding("UTF-8");
		String fmechanism = request.getParameter("fmechanism");
		fmechanism=new String(fmechanism.getBytes("iso8859-1"), "UTF-8");
		String smechanism = request.getParameter("smechanism");
		smechanism=new String(smechanism.getBytes("iso8859-1"), "UTF-8");
		String tmechanism = request.getParameter("tmechanism");
		tmechanism=new String(tmechanism.getBytes("iso8859-1"), "UTF-8");
		staff.setFmechanism(fmechanism);
		staff.setSmechanism(smechanism);
		staff.setTmechanism(tmechanism);
		List<Staff> staffs = staffService.getStaffByInstitution(staff);
		JSONArray jsonArray=new JSONArray();
		for (int j = 0; j < staffs.size(); j++) {
			JSONObject jsonObject=new JSONObject();
			Staff listStaff = staffs.get(j);
			jsonObject.put("name", listStaff.getName());
			String name = listStaff.getSalarystandard();
			String timestamp = salarystandardService.gettimestampByName(name);
			List<Salaryitem> salaryitemlist = salaryitemService.findSalaryitemByTimestamp(timestamp);
			double otherMoneys=0.00;
			for (int k = 0; k <salaryitemlist.size(); k++) {
				Salaryitem salaryitem = salaryitemlist.get(k);
				if (salaryitem.getName().equals("基本工资")) {
					jsonObject.put("item1", salaryitem.getMoney());
				}else if (salaryitem.getName().equals("养老保险")) {
					jsonObject.put("item2", salaryitem.getMoney());
				}else if (salaryitem.getName().equals("医疗保险")) {
					jsonObject.put("item3", salaryitem.getMoney());
				}else if (salaryitem.getName().equals("失业保险")) {
					jsonObject.put("item4", salaryitem.getMoney());
				}else if (salaryitem.getName().equals("住房公积金")) {
					jsonObject.put("item5", salaryitem.getMoney());
				}else {
					otherMoneys+=salaryitem.getMoney();
				}
			}
			jsonObject.put("item6", otherMoneys);
			jsonArray.add(jsonObject);
		}
		
		
		ResponseUtil.write(response, jsonArray);
		return null;
	}
	
}

